package com.example.chenz.broadcastinjava;

import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    private Button registerButton = null;
    private Button unregisterButton = null;
    private SMSReceiver smsReceiver = null;

    private static final String SMS_ACTION = "android.provider.Telephony.SMS_RECEIVED";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        registerButton = (Button)findViewById(R.id.button1);
        registerButton.setOnClickListener(new RegisterReceiverListener());

        unregisterButton = (Button)findViewById(R.id.button2);
        unregisterButton.setOnClickListener(new UnregisterReceiverListener());
    }

    class RegisterReceiverListener implements OnClickListener {

        @Override
        public void onClick(View view) {
            //生成一个BroadcastReceiver对象
            smsReceiver = new SMSReceiver();
            //生成一个IntentFilter对象
            IntentFilter intentFilter = new IntentFilter();
            //为IntentFilter生成一个action
            intentFilter.addAction(SMS_ACTION);
            //将BroadcastReceiver注册到系统当中
            MainActivity.this.registerReceiver(smsReceiver,intentFilter);
        }
    }

    class UnregisterReceiverListener implements OnClickListener {

        @Override
        public void onClick(View view) {
            //解除BroadcastReceiver对象的注册
            MainActivity.this.unregisterReceiver(smsReceiver);
        }
    }
}
